from flask import Flask, make_response, jsonify, g, current_app as app,Blueprint,request
from sqlalchemy import select,insert,update,func,join
from sqlalchemy.sql import text
from eim.tools.searchtool import SearchCondition,SearchConditionList,MatchLogic,PartnerRS,GlobalSearch
from eim.tools.dbtool import DBTool
from eim import db
from eim.result.simple_result import SimpleResult

userformbp=Blueprint("userformbp","userformbp",__name__,url_prefix='/userform')

@userformbp.route("/newUserForm",methods=["PUT"])
def newUserForm():
    """
    添加新的自定义表单
    """
    try:
        param = request.json
        pks = param.keys()
        if('cname' not in pks) or ('ename' not in pks):
            raise Exception("英文名称及中文名称不能缺失")

        # 组织待新增的自定义表单数据
        row={}
        row["ename"]=param["ename"]
        row["cname"]=param["cname"]
        if('comment' in pks):
            row["comment"]=param["comment"]
        if('status' in pks):
            row["status"]=param["status"]
        from eim.tools.dbtool import DBTool
        dbtool = DBTool(db)
        fcode=dbtool.getNewCode("userform","UF","",6)
        row['fcode']=fcode
        
        # 组织操作数据
        oprow={}
        opcode = dbtool.getNewCode("PW000018","PW000018_","",4)
        oprow["ocode"]=opcode
        oprow["oname"]=param["cname"]
        oprow["powercode"]="PW000018"
        oprow["formcode"]=fcode
        
        from eim.tools.searchtool import GlobalSearch
        gs = GlobalSearch(db)
        gs.beginTrans()
        i=gs.appentData('userform',row)
        i=gs.appentData('operate',oprow)
        gs.commit()
        return SimpleResult(status='T',value=i).toDict()
    except Exception as es:
        gs.rollback()
        info = str(es)
        app.logger.info(info)
        return SimpleResult(msg=info).toDict()

@userformbp.route("/getRowCount",methods=["POST"])
def getRowCount():
    """
    获取指定条件的表单结构记录的数量

    Returns:
        _type_: 简单数据模型
    """
    try:
        pms = request.json
        slist = SearchConditionList()
        for item in pms:
            cd = item["CD"]
            cdobj = SearchCondition(cd["field"],MatchLogic.from_Name(cd["logic"]),cd["value"])
            rs=PartnerRS.from_name(item["RS"])
            slist.appendCondition(rs,cdobj)
        from eim.tools.searchtool import GlobalSearch
        gs = GlobalSearch(db)
        rcnt = gs.getRecordCnt('userform',slist)
        return SimpleResult(status='T',value=rcnt).toDict()
    except Exception as es:
        info = str(es)
        app.logger.info(info)
        return SimpleResult(msg=info).toDict()
    
@userformbp.route("/getRows",methods=["POST"])
def getRows():
    """
    根据条件获取数据行
    """
    try:
        pms = request.json
        cols = pms["cols"]
        cds = pms["cd"]
        
        #最终的检索条件
        ps=SearchConditionList()
        
        if (len(cols)==0):
            cols=None
        if(len(cds)==0):
            ps=None
        else:
            for item in cds:
                rs = item["RS"]
                sp = PartnerRS.from_name(rs)
                field = item["CD"]["field"]
                logic = MatchLogic.from_Name(item["CD"]["logic"])
                value = item["CD"]["value"]
                so=SearchCondition(field,logic,value)
                ps.appendCondition(sp,so)
                
        from eim.tools.searchtool import GlobalSearch
        gs = GlobalSearch(db)
        result = gs.getTableData("userform",cols,ps)
        return SimpleResult(status="T",value=result).toDict()        
    except Exception as err:
        info = str(err)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@userformbp.route("/upgrade",methods=["POST"])
def upgrade():
    """
    更新自定义表单内容
    """
    try:
        pms = request.json
        vals = pms["values"]
        cds = pms["cds"]
        searchcds=SearchConditionList()
        for cd in cds:
            rs = cd["RS"]
            rso = PartnerRS.from_name(rs)
            f=cd["CD"]["field"]
            l=MatchLogic.from_Name(cd["CD"]["logic"])
            v=cd["CD"]["value"]
            sc = SearchCondition(f,l,v)
            searchcds.appendCondition(rso,sc)
        from eim.tools.searchtool import GlobalSearch
        gs = GlobalSearch(db)
        i=gs.upgradeData("userform",vals,searchcds)
        return SimpleResult(status='T',value=i).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict();
    
@userformbp.route("/getlookupdata",methods=["GET"])
def getlookupdata():
    """
    获取自定义表单列表,只包含fcode和cname两列
    """
    try:
        fl=["fcode","cname"]
        gs = GlobalSearch(db)
        result = gs.getTableData("userform",fl)
        return SimpleResult(status="T",value=result).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()